package com.lpf.MyGameSaveBackup.config.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.log.StaticLog;
import com.alibaba.fastjson.JSONObject;
import com.lpf.MyGameSaveBackup.GameSaveBackup.vo.GameSaveBackVo;
import com.lpf.MyGameSaveBackup.config.vo.GlobalConfigVo;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;

//全局配置 操作类（单例模式）
public class GlobalConfigService {
    public static GlobalConfigVo GlobalConfig;

    //获取全局配置
    public static void refreshGlobalConfig(){
        URL url = GlobalConfigService.class.getResource("/config/GlobalConfig.json");
        if (null == url){
            StaticLog.error("加载全局配置异常：配置文件(GlobalConfig.json)不存在");
        }
        String content = new FileReader(url.getPath()).readString();
        if (StringUtils.isEmpty(content)){
            StaticLog.error("加载全局配置异常：配置文件(GlobalConfig.json)内容为空");
        }
        try {
            GlobalConfigVo config = JSONObject.parseObject(content,GlobalConfigVo.class);
            if (null != config && CollUtil.isNotEmpty(config.getGameSaveBackVoList())){
                Integer index = 1;
                for (GameSaveBackVo item : config.getGameSaveBackVoList()){
                    item.setIndex(index); //根据集合顺序赋予序号，避免重复
                    index++;
                }
            }
            GlobalConfig = config;
        }
        catch (Exception e){
            StaticLog.error("加载全局配置异常：配置解析异常，请确认配置格式：");
            e.printStackTrace();
        }
    }

    //更新全局配置
    public static void updateGlobalConfig(GlobalConfigVo config){
        if (null != config && CollUtil.isNotEmpty(config.getGameSaveBackVoList())){
            Integer index = 1;
            for (GameSaveBackVo item : config.getGameSaveBackVoList()){
                item.setIndex(index); //根据集合顺序赋予序号，避免重复
                index++;
            }
        }

        URL url = GlobalConfigService.class.getResource("/config/GlobalConfig.json");
        if (null == url){
            StaticLog.error("修改全局配置异常：配置文件(GlobalConfig.json)不存在");
        }

        String content = JSONObject.toJSONString(config);
        FileWriter fileWriter = new FileWriter(url.getPath());
        fileWriter.write(content);

        GlobalConfig = config;
    }



}
